package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.BusinessException;
import com.sky.mapper.*;
import com.sky.result.Location;
import com.sky.result.PageResult;
import com.sky.service.OrdersService;
import com.sky.utils.BaiduMapUtil;
import com.sky.utils.BeanHelper;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class OrdersServiceImpl implements OrdersService {

    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private BaiduMapUtil baiduMapUtil;

    @Value("${sky.shop.address}")
    private String shopAddress;

    @Autowired
    private WebSocketServer webSocketServer;

    @Transactional
    @Override
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) throws Exception {
        log.info("用户下单 ...");
        //0 . 查询收件地址信息 , 地址为空 , 不能下单
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if(addressBook == null){
            throw new BusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        //0. 校验收获地址是否超出范围
        validateDistance(addressBook);

        //0. 购物车数据为空 , 不能下单
        ShoppingCart shoppingCart = ShoppingCart.builder().userId(BaseContext.getCurrentId()).build();
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);
        if(CollectionUtils.isEmpty(shoppingCartList)){
            throw new BusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //1. 保存订单数据 .
        Orders orders = BeanHelper.copyProperties(ordersSubmitDTO, Orders.class);
        orders.setNumber(String.valueOf(System.nanoTime())); //IdWorker -- 雪花算法 .
        orders.setStatus(Orders.ORDER_STAUTS_PENDING_PAYMENT); //待付款
        orders.setUserId(BaseContext.getCurrentId());
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.PAY_STATUS_UN_PAID); //未支付

        //收货人
        orders.setPhone(addressBook.getPhone()); //手机号
        orders.setAddress(addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee()); //收货人

        ordersMapper.insert(orders);

        //2. 保存订单明细数据 . -- 来源于购物车.
        List<OrderDetail> orderDetailList = shoppingCartList.stream().map(cart -> {
            //拷贝属性
            OrderDetail orderDetail = BeanHelper.copyProperties(cart, OrderDetail.class);
            //赋值订单ID
            orderDetail.setOrderId(orders.getId());
            return orderDetail;
        }).collect(Collectors.toList());

        orderDetailMapper.insertBatch(orderDetailList);

        //3. 清空当前用户的购物车数据 .
        shoppingCartMapper.deleteByUserId(BaseContext.getCurrentId());

        //4. 组装数据并返回 .
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderTime(orders.getOrderTime())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .build();


        //5. 推送消息给管理端 - 提醒新订单  --- {"type": 1, "orderId": 12, "content": "订单号: 273872873823"}
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("type", 1);
        paramMap.put("orderId", orders.getId());
        paramMap.put("content", "订单号: "+orders.getNumber());
        log.info("向客户端推送消息 , {}", paramMap);

        webSocketServer.sendMessageToAllClient(JSONObject.toJSONString(paramMap));
        return orderSubmitVO;
    }

    private void validateDistance(AddressBook addressBook) {
        //A. 获取店铺地址
        Location shopLocation = baiduMapUtil.getAddressGeo(shopAddress);
        log.info("获取店铺地址 : {}", shopLocation);

        //B. 获取收获地址
        Location destLocation = baiduMapUtil.getAddressGeo(addressBook.getProvinceName()+ addressBook.getCityName()+ addressBook.getDistrictName()+ addressBook.getDetail());
        log.info("获取收获地址 : {}", destLocation);

        //C. 计算两点之间距离
        Integer distance = baiduMapUtil.getDistance(shopLocation, destLocation);
        log.info("计算两点之间距离 : {}", distance);

        //D. 判断是否超出范围 , 如果超出, 抛异常
        if(distance > 5000){
            throw new BusinessException(MessageConstant.DELIVERY_OUT_OF_RANGE);
        }
    }


    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WeChatPayUtil weChatPayUtil;

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new BusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }
    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 根据订单号查询当前用户的订单
        Orders ordersDB = ordersMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.ORDER_STAUTS_TO_BE_CONFIRMED)
                .payStatus(Orders.PAY_STATUS_PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        ordersMapper.update(orders);
    }




    @Override
    public PageResult pageOrder4User(Integer page, Integer pageSize, Integer status) {
        //1. 设置分页参数
        PageHelper.startPage(page, pageSize);

        //2. 执行查询
        OrdersPageQueryDTO ordersPageQueryDTO = OrdersPageQueryDTO.builder().userId(BaseContext.getCurrentId()).status(status).build();
        List<Orders> ordersList = ordersMapper.list(ordersPageQueryDTO);

        //3. 封装分页结果
        Page<Orders> p = (Page<Orders>) ordersList;
        long total = p.getTotal();
        List<Orders> resultList = p.getResult();

        List<OrderVO> orderVOList = null;
        if (resultList != null){
            orderVOList = resultList.stream().map(orders -> {
                OrderVO orderVO = BeanHelper.copyProperties(orders, OrderVO.class);

                List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());
                orderVO.setOrderDetailList(orderDetailList);
                return orderVO;
            }).collect(Collectors.toList());
        }
        return new PageResult(total, orderVOList);
    }




    @Override
    public OrderVO getDetailById(Long id) {
        //1. 根据ID查询订单信息
        Orders orders = ordersMapper.getById(id);

        //2. 根据ID查询订单明细列表
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);

        //3. 封装数据并返回
        OrderVO orderVO = BeanHelper.copyProperties(orders, OrderVO.class);
        orderVO.setOrderDetailList(orderDetailList);

        return orderVO;
    }


    @Override
    public void cancelOrder(Long id) throws Exception {
        //1. 根据ID查询订单信息
        Orders orders = ordersMapper.getById(id);

        //2. 校验订单是否存在
        if(orders == null){
            throw new BusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //3. 校验是否可以取消订单 - 仅待支付 和 待接单 状态的订单, 可以直接取消
        Integer status = orders.getStatus();
        if(status > 2){ //  1待付款 2待接单 3已接单 4派送中 5已完成 6已取消 7退款
            throw new BusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //4. 如果订单处于待接单 且 已支付情况下 , 还需要进行退款操作
        Integer payStatus = orders.getPayStatus();
        if(status.equals(Orders.ORDER_STAUTS_TO_BE_CONFIRMED) && payStatus.equals(Orders.PAY_STATUS_PAID)){ //2 待接单 且 已支付
            //调用微信支付接口, 进行退款
            weChatPayUtil.refund(orders.getNumber(), orders.getNumber(), new BigDecimal("0.01"), new BigDecimal("0.01"));
            orders.setPayStatus(Orders.PAY_STATUS_REFUND);
        }

        //5. 更新订单状态 , 取消原因 , 取消时间等信息
        orders.setStatus(Orders.ORDER_STAUTS_CANCELLED);
        orders.setCancelReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());

        ordersMapper.update(orders);
    }


    @Override
    public void repetition(Long id) {
        //1. 根据订单ID查询订单明细数据
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);

        //2. 封装购物车列表数据
        if(orderDetailList != null){
            List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(orderDetail -> {
                ShoppingCart shoppingCart = BeanHelper.copyProperties(orderDetail, ShoppingCart.class, "id");
                shoppingCart.setCreateTime(LocalDateTime.now());
                shoppingCart.setUserId(BaseContext.getCurrentId());
                return shoppingCart;
            }).collect(Collectors.toList());

            //3. 为当前登录用户添加购物车数据
            shoppingCartMapper.insertBatch(shoppingCartList);
        }
    }




    @Override
    public PageResult search(OrdersPageQueryDTO ordersPageQueryDTO) {
        //1. 设置分页参数
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());

        //2. 执行分页查询
        List<Orders> ordersList = ordersMapper.list(ordersPageQueryDTO);

        //3. 解析分页结果
        Page<Orders> page = (Page<Orders>) ordersList;

        long total = page.getTotal();
        List<Orders> list = page.getResult();

        //处理查询出来的原始结果
        List<OrderVO> orderVOList = handleOrderVoList(list);

        return new PageResult(total, orderVOList);
    }

    private List<OrderVO> handleOrderVoList(List<Orders> list) {
        if(list != null){
            //将查询到的原始数据, 转换为 OrderVO对象
            List<OrderVO> orderVOList = list.stream().map(orders -> {
                OrderVO orderVO = BeanHelper.copyProperties(orders, OrderVO.class);

                Long orderId = orderVO.getId();
                String orderDishNames = getOrderDishNames(orderId); //获取订单中关联的菜品的明细 - 辣子鸡丁*1 ; 米饭 * 2

                orderVO.setOrderDishes(orderDishNames);
                return orderVO;
            }).collect(Collectors.toList());

            return orderVOList;
        }
        return null;
    }

    private String getOrderDishNames(Long orderId) {
        //1. 根据订单ID查询订单明细列表
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orderId);

        //2. 遍历订单明细列表, 组装订单中关联的菜品名称信息 .
        StringBuffer orderDishNames = new StringBuffer();
        if(orderDetailList != null){
            orderDetailList.stream().forEach(orderDetail -> {
                orderDishNames.append(orderDetail.getName() + "===" + orderDetail.getNumber()).append(";");
            });
        }
        return orderDishNames.toString();
    }


    @Override
    public OrderStatisticsVO statistics() {
        // 根据状态，分别查询出待接单、待派送、派送中的订单数量
        Integer toBeConfirmed = ordersMapper.countStatus(Orders.ORDER_STAUTS_TO_BE_CONFIRMED);
        Integer confirmed = ordersMapper.countStatus(Orders.ORDER_STAUTS_CONFIRMED);
        Integer deliveryInProgress = ordersMapper.countStatus(Orders.ORDER_STAUTS_DELIVERY_IN_PROGRESS);

        OrderStatisticsVO statisticsVO = OrderStatisticsVO.builder()
                .toBeConfirmed(toBeConfirmed)
                .confirmed(confirmed)
                .deliveryInProgress(deliveryInProgress)
                .build();
        return statisticsVO;
    }


    /**
     * 接单
     *
     * @param ordersConfirmDTO
     */
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = Orders.builder()
                .id(ordersConfirmDTO.getId())
                .status(Orders.ORDER_STAUTS_CONFIRMED)
                .build();

        ordersMapper.update(orders);
    }


    /**
     * 拒单
     *
     * @param ordersRejectionDTO
     */
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) throws Exception {
        // 根据id查询订单
        Orders ordersDB = ordersMapper.getById(ordersRejectionDTO.getId());

        // 订单只有存在且状态为 2 （待接单）才可以拒单
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.ORDER_STAUTS_TO_BE_CONFIRMED)) {
            throw new BusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //支付状态
        Integer payStatus = ordersDB.getPayStatus();
        if (payStatus == Orders.PAY_STATUS_PAID) {
            //用户已支付，需要退款
            String refund = weChatPayUtil.refund(
                    ordersDB.getNumber(),
                    ordersDB.getNumber(),
                    new BigDecimal(0.01),
                    new BigDecimal(0.01));
            log.info("申请退款：{}", refund);
        }

        // 拒单需要退款，根据订单id更新订单状态、拒单原因、取消时间
        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        orders.setStatus(Orders.ORDER_STAUTS_CANCELLED);
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        orders.setCancelTime(LocalDateTime.now());

        ordersMapper.update(orders);
    }


    @Override
    public void cancelByAdmin(OrdersCancelDTO ordersCancelDTO) throws Exception {
        // 根据id查询订单
        Orders ordersDB = ordersMapper.getById(ordersCancelDTO.getId());

        //支付状态
        Integer payStatus = ordersDB.getPayStatus();
        if (payStatus == Orders.PAY_STATUS_PAID) { //已支付 状态
            //用户已支付，需要退款
            String refund = weChatPayUtil.refund(
                    ordersDB.getNumber(),
                    ordersDB.getNumber(),
                    new BigDecimal(0.01),
                    new BigDecimal(0.01));
            log.info("申请退款：{}", refund);
        }

        // 管理端取消订单需要退款，根据订单id更新订单状态、取消原因、取消时间
        Orders orders = new Orders();
        orders.setId(ordersCancelDTO.getId());
        orders.setStatus(Orders.ORDER_STAUTS_CANCELLED);
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());
        ordersMapper.update(orders);
    }


    @Override
    public void delivery(Long id) {
        //1. 根据ID查询订单
        Orders orders = ordersMapper.getById(id);

        //2. 判断订单是否存在, 订单的状态是否正确
        if(orders == null || orders.getStatus() != Orders.ORDER_STAUTS_CONFIRMED){
            throw new BusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //3. 修改订单状态为 派送中
        Orders o = Orders.builder()
                .id(id)
                .status(Orders.ORDER_STAUTS_DELIVERY_IN_PROGRESS)
                .build();

        ordersMapper.update(o);
    }


    @Override
    public void complete(Long id) {
        //1. 根据ID查询订单
        Orders orders = ordersMapper.getById(id);

        //2. 判断订单是否存在, 订单的状态是否正确
        if(orders == null || orders.getStatus() != Orders.ORDER_STAUTS_DELIVERY_IN_PROGRESS){
            throw new BusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //3. 修改订单状态为 派送中
        Orders o = Orders.builder()
                .id(id)
                .status(Orders.ORDER_STAUTS_COMPLETED)
                .deliveryTime(LocalDateTime.now())
                .build();

        ordersMapper.update(o);
    }

}
